//
//  DBHelper.m
//  AddressBook
//
//  Created by  on 2020/7/29.
//  Copyright © 2020 wh. All rights reserved.
//

#import "DBHelper.h"
#import"sqlite3.h"

@implementation DBHelper
//{
//    sqlite3 *_db;// _db是数据库的句柄,即数据库的象征,如果对数据库进行增删改查,就得操作这个示例
//}

static sqlite3 *_db;

+ (void)openSqlDataBase
{
    //获取数据库文件的路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName = [docPath stringByAppendingPathComponent:@"contacta.sqlite"];
    NSLog(@"fileNamePath = %@",fileName);
    // 将 OC 字符串转换为 C 语言的字符串
    const char *cFileName = fileName.UTF8String;
    
    int result = sqlite3_open(cFileName, &_db);
    if (result == SQLITE_OK) {  // 打开成功
        NSLog(@"成功打开数据库");
        // 创建表
        const char *sql = "CREATE TABLE IF NOT EXISTS t_contactsTable (name text PRIMARY KEY,phone text NOT NULL,address text,image text NOT NULL);";
        char *errMsg = NULL;
        
        result = sqlite3_exec(_db, sql, NULL, NULL, &errMsg);
        if (result == SQLITE_OK) {
            NSLog(@"创建表成功");
        } else {
            NSLog(@"创建表失败");
            printf("创表失败---%s----%s---%d",errMsg,__FILE__,__LINE__);
        }
        
    } else {
        NSLog(@"打开数据库失败");
    }
}


+ (void)insertDataWithName:(NSString *)name
                     phone:(NSString *)phone
                   address:(NSString *)address
                     image:(NSString *)image
              successBlock:(nonnull void (^)(void))successBlock
              failureBlock:(nonnull void (^)(NSString * _Nonnull))failureBlock
{
    [self openSqlDataBase];
     // 拼接 sql 语句
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_contactsTable (name,phone,address,image) VALUES ('%@','%@','%@','%@')",name,phone,address,image];
    // 执行 sql 语句
    char *errMsg = NULL;
    int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errMsg);
    if (result == SQLITE_OK) {
        NSLog(@"插入数据成功 - %@",name);
        if (successBlock) {
            successBlock();
        }
    } else {
        NSLog(@"插入数据失败 - %s",errMsg);
        if (failureBlock) {
            failureBlock([NSString stringWithFormat:@"%s",errMsg]);
        }
    }
}
+ (void)searchWithsuccessBlock:(void (^)(NSMutableArray * _Nonnull))successBlock
                  failureBlock:(void (^)(NSString * _Nonnull))failureBlock
{
    [self openSqlDataBase];
    NSMutableArray *nameArray = [[NSMutableArray alloc]init];
    const char *sql = "SELECT * FROM t_contactsTable;";
    sqlite3_stmt *stmt = NULL;
    if (sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL) == SQLITE_OK) {
        // 每调用一次sqlite3_step函数，stmt就会指向下一条记录
        while (sqlite3_step(stmt) == SQLITE_ROW) {  // 找到一条记录
            // 取出数据
            const char *name = (char *)sqlite3_column_text(stmt, 0);   // 取出第0列字段的值
            [nameArray addObject:[[NSString alloc] initWithUTF8String:name]];
        }
        if (successBlock){
            successBlock(nameArray);
        }
    }else{
        if (failureBlock){
            failureBlock(@"查询语句有问题");
        }
    }
}

+ (void)searchWithName:(NSString *)name
                      successBlock:(nonnull void (^)(NSMutableArray * _Nonnull))successBlock
                      failureBlock:(nonnull void (^)(NSString * _Nonnull))failureBlock
{
    [self openSqlDataBase];
    NSLog(@"%@",name);
    NSMutableArray *contactsArr = [[NSMutableArray alloc]init];
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM t_contactsTable WHERE name='%@';",name];
    const char *sql = [sqlStr UTF8String];
    sqlite3_stmt *stmt = NULL;
    if (sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL) == SQLITE_OK) {
        // 每调用一次sqlite3_step函数，stmt就会指向下一条记录
        while (sqlite3_step(stmt) == SQLITE_ROW) {  // 找到一条记录
            // 取出数据
            const char *name = (char *)sqlite3_column_text(stmt, 0);   // 取出第0列字段的值
            const char *phone = (char *)sqlite3_column_text(stmt, 1);
            const char *address = (char *)sqlite3_column_text(stmt, 2);
            const char *imageStr = (char *)sqlite3_column_text(stmt, 3);
            [contactsArr addObject:[[NSString alloc] initWithUTF8String:name]];
            [contactsArr addObject:[[NSString alloc] initWithUTF8String:phone]];
            [contactsArr addObject:[[NSString alloc] initWithUTF8String:address]];
            [contactsArr addObject:[[NSString alloc] initWithUTF8String:imageStr]];
        }
        if (successBlock){
            successBlock(contactsArr);
        }
    }else{
        if (failureBlock) {
            failureBlock(@"查询语句有问题");
        }
    }
}



+ (void)deleteWithName:(NSString *)name
          successBlock:(nonnull void (^)(void))successBlock
          failureBlock:(nonnull void (^)(NSString * _Nonnull))failureBlock
{
    [self openSqlDataBase];
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM t_contactsTable WHERE name = '%@';",name];
    char *errMsg = NULL;
    int result = sqlite3_exec(_db, sqlStr.UTF8String, NULL, NULL, &errMsg);
    if (result == SQLITE_OK) {
        NSLog(@"删除数据成功 - %@",name);
        if (successBlock){
            successBlock();
        }
    } else {
        NSLog(@"删除数据失败 - %s",errMsg);
        if (failureBlock) {
            failureBlock([NSString stringWithFormat:@"%s",errMsg]);
        }
    }
}

//- (void)updateWithName:(NSString *)name phone:(NSString *)phone address:(NSString *)address
//{
//    NSString *sqlStr = [NSString stringWithFormat:@"UPDATE t_contactsTable SET phone = '%@' AND address = '%@' WHERE name='%@';",phone,address,name];
//    char *errMsg = NULL;
//    int result = sqlite3_exec(_db, sqlStr.UTF8String, NULL, NULL, &errMsg);
//    if (result == SQLITE_OK) {
//        NSLog(@"更新数据成功 - %@",name);
//    } else {
//        NSLog(@"更新数据失败 - %s",errMsg);
//    }
//
//}
@end
